package com.huixiong.nio.communicate;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.huixiong.utils.NioUtils.debugRead;

/**
 * <描述>
 *
 * @author timothy.yang cloudwise
 * @since 2022-07-05 11:46
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        // 设置为非阻塞模式
        ssc.configureBlocking(false);

        List<SocketChannel> channels = new ArrayList<>();

        ByteBuffer buffer = ByteBuffer.allocate(16);


        while (true) {
            // 接受一个client 的连接
            SocketChannel accept = ssc.accept();

            // 设置为 非阻塞模式
            accept.configureBlocking(false);
            // 将channel 添加到 列表中
            channels.add(accept);
            System.out.println("add channel: " + accept);
            for (SocketChannel channel : channels) {
                channel.read(buffer);
                // 设置为可读模式
                buffer.flip();
                System.out.println("add channel: " + accept);
                debugRead(buffer);
                buffer.clear();
            }
        }
    }
}
